package com.haojiang.mh.widget;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import androidx.annotation.Keep;
import androidx.annotation.Nullable;
import com.haojiang.mh.R;
import com.haojiang.mh.utils.ImageUtil;
import com.haojiang.mh.utils.SizeUtil;

/**
 * Created by ZapFive on 2018/1/10.
 * <p>
 * wuzhuang@mirahome.me
 */

public class TopTabLayout extends View {

    private static final String TAG = "TopTabLayout";
    public static final int SLIDE_PRE = 0;
    public static final int SLIDE_RUNNING = 1;
    public static final int SLIDE_END = 2;
    private Paint mainPaint;
    private TextPaint textPaint;
    private int width, height, defaultWidth, defaultHeight;
    private float padding, tabWidth, tabHeight, tabLeft, iconWidth, iconHeight, iconPadding, textPadding;
    private int normalTextColor, selectTextColor, tabColor;
    private int selectTabIndex = 0, switchTabIndex = -1;//选中Tab，将要切换到的Tab
    private boolean isRunning = false;
    private OnTabSelectListener listener;
    private ObjectAnimator animator;
    private Bitmap leftIconNormal, leftIconSelect, rightIconNormal, rightIconSelect;
    private String leftText, rightText;
    private RectF rectF = new RectF();

    public TopTabLayout(Context context) {
        this(context, null);
    }

    public TopTabLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TopTabLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        padding = SizeUtil.dp2px(context, 1);
        tabWidth = SizeUtil.dp2px(context, 80);
        tabHeight = SizeUtil.dp2px(context, 34);
        iconPadding = SizeUtil.dp2px(context, 14);
        iconWidth = SizeUtil.dp2px(context, 17);
        iconHeight = SizeUtil.dp2px(context, 14);
        textPadding = SizeUtil.dp2px(context, 20);
        tabLeft = padding;
        defaultWidth = (int) ((padding + tabWidth) * 2);
        defaultHeight = (int) (padding * 2 + tabHeight);

        tabColor = getResources().getColor(R.color.color_golden_dark_n);
        normalTextColor = getResources().getColor(R.color.grey_2);
        selectTextColor = getResources().getColor(R.color.white);

        leftIconNormal = ImageUtil.getBitmapFromDrawable(context, R.drawable.ic_double_user_left_normal);
        leftIconSelect = ImageUtil.getBitmapFromDrawable(context, R.drawable.ic_double_user_left_select);
        rightIconNormal = ImageUtil.getBitmapFromDrawable(context, R.drawable.ic_double_user_right_normal);
        rightIconSelect = ImageUtil.getBitmapFromDrawable(context, R.drawable.ic_double_user_right_select);
        leftText = getResources().getString(R.string.txt_top_tab_left);
        rightText = getResources().getString(R.string.txt_top_tab_right);

        mainPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mainPaint.setStyle(Paint.Style.FILL);
        mainPaint.setColor(tabColor);

        textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setTextSize(SizeUtil.sp2px(context, 15));

        animator = ObjectAnimator.ofFloat(this, "offSet", 0.0f, 1.0f);
        animator.setDuration(240);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.setRepeatCount(0);
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                if (listener != null) {
                    listener.onSelect(switchTabIndex, -1, SLIDE_PRE);
                    Log.e(TAG, "onAnimationStart: 111");
                }
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                isRunning = false;
                selectTabIndex = switchTabIndex;
                if (listener != null) {
                    listener.onSelect(switchTabIndex, -1, SLIDE_END);
                    Log.e(TAG, "onAnimationStart: 222");
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
    }

    @Keep
    public void setOffSet(float offSet) {
        isRunning = true;
        if (switchTabIndex == 0) {
            tabLeft = padding + tabWidth * (1 - offSet);
        } else if (switchTabIndex == 1) {
            tabLeft = padding + tabWidth * offSet;
        }
        if (listener != null) {
            listener.onSelect(switchTabIndex, offSet, SLIDE_RUNNING);
        }
        invalidate();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        rectF.set(tabLeft, padding, tabLeft + tabWidth, height - padding);
        canvas.drawRoundRect(rectF, tabHeight / 2, tabHeight / 2, mainPaint);

        //左侧icon和Text绘制
        canvas.drawBitmap(
                selectTabIndex == 0 ? leftIconSelect : leftIconNormal,
                padding + iconPadding,
                (height - iconHeight) / 2,
                null
        );
        textPaint.setColor(selectTabIndex == 0 ? selectTextColor : normalTextColor);
        canvas.drawText(
                leftText,
                padding + (tabWidth + textPadding) / 2,
                SizeUtil.getBaseLine(textPaint, height - padding, tabHeight),
                textPaint
        );

        //右侧icon和Text绘制
        canvas.drawBitmap(
                selectTabIndex == 1 ? rightIconSelect : rightIconNormal,
                padding + iconPadding + tabWidth,
                (height - iconHeight) / 2,
                null
        );
        textPaint.setColor(selectTabIndex == 1 ? selectTextColor : normalTextColor);
        canvas.drawText(
                rightText,
                padding + tabWidth + (tabWidth + textPadding) / 2,
                SizeUtil.getBaseLine(textPaint, height - padding, tabHeight),
                textPaint
        );
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(
                getMeasuredLength(widthMeasureSpec, true),
                getMeasuredLength(heightMeasureSpec, false)
        );
    }

    private int getMeasuredLength(int length, boolean isWidth) {
        int specMode = MeasureSpec.getMode(length);
        int specSize = MeasureSpec.getSize(length);
        int size;
        int padding = isWidth ? getPaddingLeft() + getPaddingRight() : getPaddingTop() + getPaddingBottom();
        if (specMode == MeasureSpec.EXACTLY) {
            size = specSize;
        } else if (specMode == MeasureSpec.UNSPECIFIED) {
            size = isWidth ? defaultWidth : defaultHeight;
        } else {
            size = isWidth ? padding + defaultWidth : padding + defaultHeight;
            if (specMode == MeasureSpec.AT_MOST) {
                size = Math.min(size, specSize);
            }
        }
        return size;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (isRunning) return false;
            float x = event.getX();
            if (selectTabIndex == 0) {
                if (x >= padding + tabWidth && x <= width - padding) {
                    switchTabIndex = 1;
                    if (animator != null){
                        animator.start();
                    }
                }
            } else if (selectTabIndex == 1) {
                if (x >= padding && x <= width - padding - tabWidth) {
                    switchTabIndex = 0;
                    if (animator != null){
                        animator.start();
                    }
                }
            }
        }
        return true;
    }

    @Override
    protected void onDetachedFromWindow() {
        if (animator != null) {
            if (animator.isRunning()) {
                animate().cancel();
            }
            animator = null;
            System.gc();
        }
        super.onDetachedFromWindow();
    }

    public void setOnTabSelectListener(OnTabSelectListener listener) {
        this.listener = listener;
    }

    public int getSelectTabIndex() {
        return selectTabIndex;
    }

    public void resetSelectTab() {
        switchTabIndex = selectTabIndex = 0;
        tabLeft = padding;
        invalidate();
    }

    public interface OnTabSelectListener {
        /**
         * @param selectTabIndex 选中Tab下标
         * @param flag           0:pre 1:running 2:end
         */
        void onSelect(int selectTabIndex, float offset, int flag);
    }
}
